package com.weipu.common.util;

import android.text.TextUtils;

import com.weipu.common.constants.Constant;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

public class SecurityUtil {
	private static byte[] keyValue;

	private static byte[] iv;

	private static SecretKey key;
	private static AlgorithmParameterSpec paramSpec;
	private static Cipher ecipher;

	static {
		System.loadLibrary("EncryptLib");
		keyValue = getKeyValue();
		iv = getIv();
//
//		if (null != keyValue && null != iv) {
//			KeyGenerator kgen;
//			try {
//				kgen = KeyGenerator.getInstance("AES");
//				kgen.init(128, new SecureRandom(keyValue));
//				key = kgen.generateKey();
//				paramSpec = new IvParameterSpec(iv);
//				ecipher = Cipher
//						.getInstance("AES/CBC/PKCS5Padding"/* "AES/ECB/PKCS5Padding" */);
//			} catch (NoSuchAlgorithmException e) {
//			} catch (NoSuchPaddingException e) {
//			}
//		}
	}

	public static native byte[] getKeyValue();

	public static native byte[] getIv();

	public static String encode(String msg) {
		String str = "";
		try {
			// 用密钥和一组算法参数初始化此 cipher
			ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
			// 加密并转换成16进制字符串
			// str = asHex(ecipher.doFinal(msg.getBytes()));
			// 加密转成BASE64输出
			str = new BASE64Encoder().encode(ecipher.doFinal(msg.getBytes()));

		} catch (BadPaddingException e) {
		} catch (InvalidKeyException e) {
		} catch (InvalidAlgorithmParameterException e) {
		} catch (IllegalBlockSizeException e) {
		}
		return str;
	}

	public static String decode(String value) {
		try {
			ecipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
			byte[] bytes = new BASE64Decoder().decodeBuffer(value);
			// return new String(ecipher.doFinal(asBin(value)));
			return new String(ecipher.doFinal(bytes));
		} catch (BadPaddingException e) {
		} catch (InvalidKeyException e) {
		} catch (InvalidAlgorithmParameterException e) {
		} catch (IllegalBlockSizeException e) {
		} catch (IOException e) {
		}
		return "";
	}

	private static String asHex(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i;
		for (i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10)// 小于十前面补零
				strbuf.append("0");
			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}
		return strbuf.toString();
	}

	private static byte[] asBin(String src) {
		if (src.length() < 1)
			return null;
		byte[] encrypted = new byte[src.length() / 2];
		for (int i = 0; i < src.length() / 2; i++) {
			int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);// 取高位字节
			int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);// 取低位字节
			encrypted[i] = (byte) (high * 16 + low);
		}
		return encrypted;
	}

	/**
	 * ECB模式加密 无偏移量 输出Base64
	 * 
	 * @param str
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String aesEncrypt(String str/*, byte[] key*/) throws Exception {
		if (str == null || keyValue == null)
			return null;
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		// ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(/*
															 * key.getBytes("utf-8"
															 * )
															 */keyValue, "AES"));
		byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
		return new BASE64Encoder().encode(bytes);
	}

	/**
	 * ECB模式解密无
	 * 
	 * @param str
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String aesDecrypt(String str/*, byte[] key*/) throws Exception {
		if (str == null || keyValue == null)
			return null;
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		// ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(/*
															 * key.getBytes("utf-8"
															 * )
															 */keyValue, "AES"));
		byte[] bytes = new BASE64Decoder().decodeBuffer(str);
		bytes = cipher.doFinal(bytes);
		return new String(bytes, "utf-8");
	}
	
}
